package org.dizem.minichat.service;

import org.dizem.minichat.util.VOUtil;
import org.dizem.minichat.vo.DataPacket;
import org.dizem.minichat.vo.MessageVO;
import org.dizem.minichat.vo.Operation;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * User: DIZEM
 * Time: 11-3-26 上午9:45
 */
public class ChatSkelImpl implements IChatSkel {

	private String clientAddress;
	private int clientPort;

	public ChatSkelImpl(String clientAddress, int clientPort) {
		this.clientAddress = clientAddress;
		this.clientPort = clientPort;
	}

	private void send(DataPacket dp) {
		try {
			DatagramSocket ds = new DatagramSocket();
			String message = VOUtil.convertVOTo2String(dp);

			byte[] data = message.getBytes("UTF-8");

			DatagramPacket packet = new DatagramPacket(
					data,
					data.length,
					InetAddress.getByName(clientAddress),
					clientPort
			);

			ds.send(packet);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void response(String msg) {
		send(new DataPacket(Operation.RESPONSE, msg));
	}

	public void sendMessage(MessageVO messageVO) {
		send(new DataPacket(messageVO));
	}


}
